package com.tuuzed.android.util;

import android.content.Context;
import android.support.annotation.NonNull;
import android.widget.Toast;

public final class ToastUtil {
    private static Toast sToast;
    private static int sGravity = -1;
    private static int sXOffset = -1;
    private static int sYOffset = -1;

    public static void setGravity(int gravity, int xOffset, int yOffset) {
        sGravity = gravity;
        sXOffset = xOffset;
        sYOffset = yOffset;
    }

    public static void showShort(@NonNull final Context context, @NonNull final CharSequence text) {
        MainHandlerUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                show(context, text, false);
            }
        });
    }

    public static void showLong(@NonNull final Context context, @NonNull final CharSequence text) {
        MainHandlerUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                show(context, text, true);
            }
        });
    }

    public static void cancel() {
        if (sToast != null) {
            sToast.cancel();
        }
    }

    private static void show(@NonNull final Context context, @NonNull CharSequence text, boolean isLong) {
        cancel();
        sToast = Toast.makeText(context.getApplicationContext(), text, isLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
        if (sGravity != -1 || sXOffset != -1 || sYOffset != -1) {
            sToast.setGravity(sGravity, sXOffset, sYOffset);
        }
        sToast.show();
    }
}
